package com.gistmap.sideline.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 邮箱激活码的缓存
 */
@Slf4j
public enum  CodeCache {

    INSTANCE;

    private static Cache<String, Long> cache;
    static {
        cache = CacheBuilder.newBuilder().maximumSize(100)
                .expireAfterWrite(24, TimeUnit.HOURS)
                .initialCapacity(10)
                .removalListener((RemovalListener<String, Long>) rn -> {
                    if(log.isInfoEnabled()){
                        log.info("被移除缓存{}:{}",rn.getKey(), rn.getValue());
                    }
                }).build();
    }

    public void put(Long value, String key) {
        if (StringUtils.isNotEmpty(key) && value != null){
            cache.put(key, value);
        }
    }

    public Long get(String key) {
        return key != null ? cache.getIfPresent(key) : null;
    }

    public void remove(String key){
        if (StringUtils.isNotEmpty(key)) {
            cache.invalidate(key);
        }
    }


}
